
var materialArray;
var baseUrl="/weixin/";
var  table;
//相关业务逻辑
$(function(){
	page.bindTag();
	page.getAllMaterial();
	page.getProductionDepartment();
	page.getMaterialProcedure("");
	page.removeBtnBind();
	page.remove();
});

var page={//页面总变量 
		//绑定页面元素
		first:'desc',
		second:'desc',
		third:'desc',
		saveOtherId:'',
		materialTypeArray:[],
		bindTag:function(){
			/**
			 * 第一个排序
			 */
			$(".firstA").bind("click",function(){
				var keySort="";
				if(page.first=='desc'){
					keySort="firstSort asc";
					page.first="asc";
				}else{
					keySort="firstSort desc";
					page.first="desc";
				}
				page.getMaterialProcedure(keySort);
			});
			
			
			/**
			 * 第二个排序
			 */
			$(".secondA").bind("click",function(){
				var keySort="";
				if(page.second=='desc'){
					keySort="secondSort asc";
					page.second="asc";
				}else{
					keySort="secondSort desc";
					page.second="desc";
				}
				page.getMaterialProcedure(keySort);
			});
			
			
			/**
			 * 第三个排序
			 */
			$(".thirdA").bind("click",function(){
				var keySort="";
				if(page.third=='desc'){
					keySort="firstSort asc";
					page.third="asc";
				}else{
					keySort="firstSort desc";
					page.third="desc";
				}
				page.getMaterialProcedure(keySort);
			});
			
			
			/**
			 * 设置工序加工对象的时候，改变物料类型
			 */
			$("#publicMaterialType").bind("change",function(){
				page.materialTypeChange("publicMaterialType","publicMaterialArts");
//				page.materialTypeChange("publicMaterialType","publicMaterialName","publicMaterialArts","publicMaterialQuality");
			});
			
			
//			//选择物料类型
			$("#materialType").bind("change",function(){
				page.materialTypeChange("materialType","arts");
			});
			
			//工序另存为
            $("#saveOtherMaterialType").bind("change",function(){
            	page.materialTypeChange("saveOtherMaterialType","saveOtherMaterialArts");
//            	page.materialTypeChange("saveOtherMaterialType","saveOtherMaterialName","saveOtherMaterialArts","saveOtherMaterialQuality");
            });	
            
            
			/**
			 * 设置工序加工对象的时候，改变物料名称
			 */
//		    $("#publicMaterialName").bind("click",function(){
//		    	page.materialNameChange("publicMaterialType","publicMaterialName","publicMaterialQuality");
//		    });
		    
		    
		    /**
		     * 工序存为物料明恒该表的时候
		     */
//		    $("#saveOtherMaterialName").bind("click",function(){
//		    	page.materialNameChange("saveOtherMaterialType","saveOtherMaterialName","saveOtherMaterialQuality");
//		    });
			
			//选择物料名称
//			$("#materialName").bind("click",function(){
//				page.materialNameChange("materialType","materialName","materialQuality");
//			});
			
			/**
			 * 点击查询按钮
			 */
			$("#queryCombinationBtn").bind("click",function(){
				page.getMaterialProcedure("");
			});
			
			/**
			 * 添加组合，点击弹出模态框
			 */
			$("#addCombinationBtn").bind("click",function(){
				$("#addCombinationModal").modal("show");
			});
			
			/**
			 * 选择部门时重新设置工序
			 */
			$("#deptId").bind("change",function(){
				var deptId=$(this).val();
				page.getDeptProcedure(deptId);
				$("#addCombinationModal .right-box").html("");
			});
			
			
			/**
			 *  模态框添加组合，实际保存数据
			 */
			$("#addCombinationModalBtn").bind("click",function(){
				page.addCombination();
			});
			
			/**
			 * 删除组合
			 */
			$("#materialProcedureTable tbody").on("click",".deleteCombination",function(){
				var input=$(this);
				layer.confirm('确定删除此组合？', {
					  btn: ['删除','取消'] //按钮
					}, function(){
						var id=input.val();
						ajaxUtil.ajaxRuquest(baseUrl+"partsProcedure/deleteCombination",{"id":id},function(data){
							layer.msg(data,{icon:1});
							table.ajax.reload(null,false);
						});
					});
			});
			
			/**
			 * 鼠标移动tips
			 */
			$("#materialProcedureTable tbody").on("mouseover",".tips",function(){
				var otherMaching=$(this).attr("otherMaching");
				if(otherMaching==""){
					otherMaching="无";
				}
				layer.tips('加工对象：'+otherMaching, $(this), {
					  tips: [1, '#0FA6D8'] //还可配置颜色
				});
			});
			
			/**
			 * 点击设置加工对象
			 */
			$("#materialProcedureTable tbody").on("click",".tips",function(){
				var otherMaching=$(this).attr("otherMaching");
				var procedureId=$(this).val();
				var procedureName=$(this).text();
				var combinationId=$(this).parent().next().next().next().next().children(".deleteCombination").val();
				if(otherMaching==""){
					otherMaching="无";
				}
				$("#publicMaterialType").val("");
				$("#publicMaterialName option[value='']").attr("selected", "selected");
				$("#publicMaterialQuality option[value='']").attr("selected", "selected");
				$("#publicMaterialArts option[value='']").attr("selected", "selected");
				$("#setProcedureMachingModalCombinationId").val(combinationId);
				$("#setProcedureMachingModalProcedureId").val(procedureId);
				$("#procedureName").text(procedureName);
				$("#maching").text(otherMaching);
				$("#setProcedureMachingModal").modal("show");
			});
			
			
			
			/**
			 * 设置组合工序
			 */
			$("#materialProcedureTable tbody").on("click",".setCombination",function(){
				var id=$(this).val();
				page.getMaterialHaveAndNoHaveProcedure(id);
			});
			
			
			
			/**
			 * 设置组合排序
			 */
			$("#materialProcedureTable tbody").on("click",".setCombinationSort",function(){
				var object=new Object();
				object.id=$(this).val();
				object.firstSort=$(this).parent().prev().prev().prev().text();
				object.secondSort=$(this).parent().prev().prev().text();
				object.thirdSort=$(this).parent().prev().text();
				ajaxUtil.ajaxRuquest(baseUrl+"partsProcedure/setCombinationSort",object,function(data){
				   layer.msg(data,{icon:1});
				   $("#setProcedureMachingModal").modal("hide");
				   table.ajax.reload(null,false);
				});
			});
			
			
			/**
			 * 保存修改
			 */
			$("#setCombinationModalBtn").bind("click",function(){
				page.setCombinationProcedure();
			});
			
			/**
			 * 保存另存为的工序
			 */
			$("#saveOtherModalBtn").bind("click",function(){
				var  object=new Object();
				object.materialType=$("#saveOtherMaterialType").val();
				object.materialName=$("#saveOtherMaterialName option:selected").val();
				object.materialQuality=$("#saveOtherMaterialQuality option:selected").val();
				object.arts=$("#saveOtherMaterialArts option:selected").val();
				object.beforeId=page.saveOtherId;
				if(object.materialType==''){
					layAlert("请选择物料类型");
					return false;
				}
				if($.inArray(object.materialType, page.materialTypeArray)==-1){
					layAlert("物料类型不存在");
					return false;
				}
				
				ajaxUtil.ajaxRuquest(baseUrl+"partsProcedure/saveOtherCombination",object,function(data){
					layer.msg(data,{icon:1});
					$("#saveOtherModal").modal("hide");
					table.ajax.reload(null,false);
				});
			});
			
			
			/**
			 * 添加模态框模糊查询工序
			 */
			$("#addSearchWhereBtn").bind("click",function(){
				var deptId=$("#deptId option:selected").val();
				if(deptId==""){
					layAlert("请选择部门");
					return false;
				}
				page.getDeptProcedure(deptId);
			});
			
			/**
			 * 设置查询工序
			 */
		   $("#setSearchWhereBtn").bind("click",function(){
			   page.getCombinationNoHaveProcrdere();
		   });
		   
		   /**
		    * 设置加工对象
		    */
		   $("#setProcedureMachingModalBtn").bind("click",function(){
			   var object=new Object();
			   object.maching=$("#publicMaterialType").val();
			   if($.inArray(object.maching, page.materialTypeArray)==-1 && object.maching!=''){
					layAlert("物料类型不存在");
					return false;
				}
			   
//			   object.materialName=$("#publicMaterialName option:selected").val();
//			   object.materialQuality=$("#publicMaterialQuality option:selected").val();
			   object.arts=$("#publicMaterialArts option:selected").val();
			   object.combinationId=$("#setProcedureMachingModalCombinationId").val();
			   object.procedureId=$("#setProcedureMachingModalProcedureId").val();
			   ajaxUtil.ajaxRuquest(baseUrl+"partsProcedure/setProcedureMaching",object,function(data){
				   layer.msg(data,{icon:1});
				   $("#setProcedureMachingModal").modal("hide");
				   table.ajax.reload(null,false);
				});
		   });
		   
		   
		   /**
			 * 工序另存为
			 */
			$("#materialProcedureTable tbody").on("click",".saveOther",function(){
				var id=$(this).val();
				page.saveOtherId=id;
				$("#saveOtherMaterialType").val("");
//				$("#saveOtherMaterialName option[value='']").attr("selected", "selected");
//				$("#saveOtherMaterialQuality option[value='']").attr("selected", "selected");
				$("#saveOtherMaterialArts option[value='']").attr("selected", "selected");
				$("#saveOtherModal").modal("show");
			});
			
		   /**
		    * 导出为excle
		    */
		   $("#downlodeExcle").bind("click",function(){
			    var pageSerachWhere=$("#pageSerachWhere").val();
				var url=baseUrl+"partsProcedure/downlodeCombinationKeyPrucedureData?searchWhere="+pageSerachWhere;
				tableUtil.download(url);
		   });
		},
//		materialNameChange:function(materialType,materialName,materialQuality){
//			 var materialType=$("#"+materialType).val();
//			 var materialName=$("#"+materialName).val();
//			 
//			 var materialTypeArray=_.filter(materialArray,{materialType:materialType,materialName:materialName});
//			 var materialQualityArray=_.map(materialTypeArray,"materialQuality");
//			 materialQualityArray=_.filter(materialQualityArray,function(xx){
//					return xx!='';
//			 });
//			 materialQualityArray=_.uniq(materialQualityArray);
//			 var html="<option value=''>请选择</option>";
//			 for(var i=0;i<materialQualityArray.length;i++){
//					 html+="<option value='"+materialQualityArray[i]+"'>"+materialQualityArray[i]+"</option>";
//			 }
//			 $("#"+materialQuality).html(html);
//		},
		materialTypeChange:function(materialType,arts){
//			materialTypeChange:function(materialType,materialName,arts,materialQuality){
			var materialType=$("#"+materialType).val();
//			var html="<option value=''>请选择</option>";
			var artsHtml="<option value=''>请选择</option>";
			
			//获取物料类型对应的物料信息
			var materialTypeArray=_.filter(materialArray,{materialType:materialType});
			//获取对应的物料类型
//			var materialNameArray=_.map(materialTypeArray, "materialName");
//			materialNameArray=_.filter(materialNameArray,function(xx){
//				return xx!='';
//			});
//			materialNameArray=_.uniq(materialNameArray);
//			for(var i=0;i<materialNameArray.length;i++){
//				html+="<option value='"+materialNameArray[i]+"'>"+materialNameArray[i]+"</option>";
//			}
			
			var artsArray=_.map(materialTypeArray, "arts");
			artsArray=_.filter(artsArray,function(xx){
				return xx!='';
			});
			artsArray=_.uniq(artsArray);
			for(var i=0;i<artsArray.length;i++){
				artsHtml+="<option value='"+artsArray[i]+"'>"+artsArray[i]+"</option>";
			}
			
//			$("#"+materialName).html(html);
			$("#"+arts).html(artsHtml);
//			$("#"+materialQuality).html("<option value=''>请选择</option>");
		},
		getAllMaterial:function(){
			ajaxUtil.ajaxRuquest(baseUrl+"partsProcedure/getCompanyMaterial",null,function(data){
				materialArray=data;
				var materialTypeArray=_.map(data, "materialType");
				materialTypeArray=_.uniq(materialTypeArray);
				page.materialTypeArray=materialTypeArray;
				var html="<option value=''>请选择</option>";
				for(var i=0;i<materialTypeArray.length;i++){
					html+="<option value='"+materialTypeArray[i]+"'>"+materialTypeArray[i]+"</option>";
				}
				$("#addMaterialList").html(html);
				$("#publicMaterialList").html(html);
				$("#saveOtherMaterialList").html(html);
			});
		},
		getProductionDepartment:function(){
			ajaxUtil.ajaxRuquest(baseUrl+"basicData/getProductionDepartment",null,function(data){
				var html="<option value=''>请选择</option>";
				for(var i=0;i<data.length;i++){
						html+="<option value='"+data[i].id+"'>"+data[i].deptName+"</option>";
				}
				$("#deptId").html(html);
			});
		},
		getMaterialProcedure:function(keySort){
			var pageSerachWhere=$("#pageSerachWhere").val();
			table=ajaxUtil.dataTablesAjax("materialProcedureTable",10,baseUrl+"partsProcedure/getMaterialProcedure",
					{'searchWhere':pageSerachWhere,"keySort":keySort},[
						{"data":"materialType",render: function (data,type,row){
							var html=data;
//							if(row.materialName!=''){
//								html+="-"+row.materialName;
//							}
//							if(row.materialQuality!=''){
//								html+="-"+row.materialQuality;
//							}
							if(row.arts!=''){
								html+="+"+row.arts;
							}
							return html;
						}},
						{"data":"procedureList",render: function (data,type,row){
							var html="";
							for(var i=0;i<data.length;i++){
								var otherMaching=data[i].otherMaching;
//								if(data[i].materialName!=''){
//									otherMaching+="-"+data[i].materialName;
//								}
//								if(data[i].materialQuality!=''){
//									otherMaching+="-"+data[i].materialQuality;
//								}
								if(data[i].arts!=''){
									otherMaching+="+"+data[i].arts;
								}
								html+=" <button class='btn tips' value='"+data[i].procedureId+"' otherMaching='"+otherMaching+"'>"+data[i].workShopName+'-'+data[i].procedureName+"</button>";
							}
							return html;
						}},
						{"data":"firstSort"},
						{"data":"secondSort"},
						{"data":"thirdSort"},
						{"data":"id",render: function (data,type,row){
							return "<button class='btn btn-link deleteCombination' value='"+data+"'>删除</button>" +
								   "<button class='btn btn-link setCombination' value='"+data+"' >设置工序</button>"+
								   "<button class='btn btn-link saveOther' value='"+data+"' >工序另存为</button>"+
							       "<button class='btn btn-link setCombinationSort' value='"+data+"' >设置排序</button>";
						}}
			        ],[2,3,4],function(td, cellData, rowData, row, col){
						 $(td).attr("contenteditable",true);
					}
				);
		},
		getDeptProcedure:function(deptId){
			var searchWhere=$("#addSearchWhereInput").val();
			ajaxUtil.ajaxRuquest(baseUrl+"partsProcedure/getDeptProcedure",{"deptId":deptId,"searchWhere":searchWhere},function(data){
				var html="";
				for(var i=0;i<data.length;i++){
					html+="<li class='item ui-sortable-handle'  data-id="+data[i].id+">"+data[i].workshopName+'-'+data[i].processName+"</li>";
				}
				$("#addCombinationModal .left-box").html(html);
//				$("#addCombinationModal .right-box").html("");
				page.leftAndRightBind();
			});
		},
		addCombination:function(){
			var  materialType=$("#materialType").val();
//			var  materialName=$("#materialName option:selected").val();
//			var  materialQuality=$("#materialQuality option:selected").val();
			var  deptId=$("#deptId option:selected").val();
			var  arts=$("#arts option:selected").val();
			if(materialType==''){
				layAlert("请选择物料类型");
				return false;
			}
			if($.inArray(materialType, page.materialTypeArray)==-1){
				layAlert("物料类型不存在");
				return false;
			}
			if(deptId==''){
				layAlert("请选择部门");
				return false;
			}
			var array=new Array();
			var i=1;
			$("#addCombinationModal .right-box").find(".ui-sortable-handle").each(function(){
				var pro=new Object();
				pro.id=$(this).attr("data-id");
				pro.sort=i;
				array.push(pro);
				i++;
			});
			if(array.length<=0){
				layAlert("请选择要添加的工序");
				return false;
			}	
			var sendDate=new Object();
			sendDate.materialType=materialType;
//			sendDate.materialName=materialName;
//			sendDate.materialQuality=materialQuality;
			sendDate.deptId=deptId;
			sendDate.arts=arts;
			sendDate.procedureArray=JSON.stringify(array);
			ajaxUtil.ajaxRuquest(baseUrl+"partsProcedure/addCombination",sendDate,function(data){
				layer.msg(data,{icon:1});
				$("#addCombinationModal").modal("hide");
				table.ajax.reload(null,false);
			});
		},
		setCombinationProcedure:function(){
			var id=$("#setModalCombinationId").val();
			var array=new Array();
			var i=1;
			$("#setCombinationModal .right-box").find(".ui-sortable-handle").each(function(){
				var pro=new Object();
				pro.id=$(this).attr("data-id");
				pro.maching=$(this).attr("maching");
//				pro.materialName=$(this).attr("materialName");
//				pro.materialQuality=$(this).attr("materialQuality");
				pro.arts=$(this).attr("arts");
				pro.sort=i;
				array.push(pro);
				i++;
			});
			if(array.length<=0){
				layAlert("如要移除所有工序，请删除此组合");
				return false;
			}	
			ajaxUtil.ajaxRuquest(baseUrl+"partsProcedure/setCombinationProcrdure",{"id":id,"procedureArray":JSON.stringify(array)},function(data){
				layer.msg(data,{icon:1});
				$("#setCombinationModal").modal("hide");
				table.ajax.reload(null,false);
			});
		},
		getMaterialHaveAndNoHaveProcedure:function(id){
			ajaxUtil.ajaxRuquest(baseUrl+"partsProcedure/getMaterialHaveAndNoHaveProcedure",{"id":id},function(data){
				var combinationKey=data.combinationKey;
				var processListHave=data.processListHave;
				var processListNoHave=data.processListNoHave;
				var titleHtml="";
				var leftHtml="";
				var rightHtml="";
//				标题内容
				titleHtml=combinationKey.materialType+"-"+combinationKey.arts;
//				左边没有的工序
				for(var i=0;i<processListNoHave.length;i++){
					leftHtml+="<li class='item ui-sortable-handle'  data-id="+processListNoHave[i].id+">"+processListNoHave[i].workshopName+"-"+processListNoHave[i].processName+"</li>";
				}
//				右边有的工序
				for(var i=0;i<processListHave.length;i++){
					var maching=processListHave[i].maching;
					if(maching!=''){
						maching="_"+maching;
//						if(processListHave[i].materialName!=''){
//							maching+="_"+processListHave[i].materialName;
//						}
					}
					
					rightHtml+="<li class='item ui-sortable-handle'  data-id="+processListHave[i].id+" maching='"+processListHave[i].maching+"'  arts='"+processListHave[i].arts+"'>"+processListHave[i].workshopName+"-"+processListHave[i].processName+"<span style='color:red'>"+maching+"</span>"+"</li>";
				}
				$("#setModalCombinationTitle").text(titleHtml);
				$("#setModalDeptName").text(combinationKey.deptName);
				$("#setModalCombinationId").val(combinationKey.id);
				$("#setModalCombinationDeptId").val(combinationKey.deptId);
				$("#setCombinationModal .left-box").html(leftHtml);
				$("#setCombinationModal .right-box").html(rightHtml);
				$("#setCombinationModal").modal("show");
				page.leftAndRightBindSet();
			});
		},
		getCombinationNoHaveProcrdere:function(){
			var id=$("#setModalCombinationId").val();
			var deptId=$("#setModalCombinationDeptId").val();
			var searchWhere=$("#setSearchWhereInput").val();
			ajaxUtil.ajaxRuquest(baseUrl+"partsProcedure/getCombinationNoHaveProcrdere",{"id":id,"deptId":deptId,"searchWhere":searchWhere},function(data){
				var processListNoHave=data;
			    var leftHtml="";
			    for(var i=0;i<processListNoHave.length;i++){
					leftHtml+="<li class='item ui-sortable-handle'  data-id="+processListNoHave[i].id+">"+processListNoHave[i].workshopName+'-'+processListNoHave[i].processName+"</li>";
				}
			    $("#setCombinationModal .left-box").html(leftHtml);
			    page.leftAndRightBindSet();
			});
		},
		leftAndRightBind:function(){
			$(".item").unbind("click");
			$(".left-box .item").unbind("dblclick");
			$(".right-box .item").unbind("dblclick");
			//单击
			$(".item").bind("click",function(){
				$(this).toggleClass("selected-item");
			});
			
			//左边双击右移
			$(".left-box .item").bind("dblclick",function(){
				$(".right-box").append($(this).removeClass('selected-item'));
				page.leftAndRightBind();
			});
			
            //右边双击左移
			$(".right-box .item").bind("dblclick",function(){
				$(".left-box").append($(this).removeClass('selected-item'));
				page.leftAndRightBind();
			});
		},
		leftAndRightBindSet:function(){
			$("#setCombinationModal .item").unbind("click");
			$("#setCombinationModal .left-box .item").unbind("dblclick");
			$("#setCombinationModal .right-box .item").unbind("dblclick");
			//单击
			$("#setCombinationModal .item").bind("click",function(){
				$(this).toggleClass("selected-item");
			});
			
			//左边双击右移
			$("#setCombinationModal .left-box .item").bind("dblclick",function(){
				$("#setCombinationModal .right-box").append($(this).removeClass('selected-item'));
				page.leftAndRightBind();
			});
			
			//右边双击左移
			$("#setCombinationModal .right-box .item").bind("dblclick",function(){
				$("#setCombinationModal .left-box").append($(this).removeClass('selected-item'));
				page.leftAndRightBind();
			});
		},
		removeBtnBind:function(){
			$("#addCombinationModal .add-one").bind("click",function(){
				$("#addCombinationModal .right-box").append($("#addCombinationModal .left-box").find('.selected-item').removeClass('selected-item'));
			});
			
			$("#addCombinationModal .add-all").bind("click",function(){
				$("#addCombinationModal .right-box").append($("#addCombinationModal .left-box").find('.item').removeClass('selected-item'));
			});
			
			$("#addCombinationModal .remove-one").bind("click",function(){
				$("#addCombinationModal .left-box").append($("#addCombinationModal .right-box").find('.selected-item').removeClass('selected-item'));
			});
			
			$("#addCombinationModal .remove-all").bind("click",function(){
				$("#addCombinationModal .left-box").append($("#addCombinationModal .right-box").find('.item').removeClass('selected-item'));
			});
			$("#setCombinationModal .add-one").bind("click",function(){
				$("#setCombinationModal .right-box").append($("#setCombinationModal .left-box").find('.selected-item').removeClass('selected-item'));
			});
			
			$("#setCombinationModal .add-all").bind("click",function(){
				$("#setCombinationModal .right-box").append($("#setCombinationModal .left-box").find('.item').removeClass('selected-item'));
			});
			
			$("#setCombinationModal .remove-one").bind("click",function(){
				$("#setCombinationModal .left-box").append($("#setCombinationModal .right-box").find('.selected-item').removeClass('selected-item'));
			});
			
			$("#setCombinationModal .remove-all").bind("click",function(){
				$("#setCombinationModal .left-box").append($("#setCombinationModal .right-box").find('.item').removeClass('selected-item'));
			});
		},
		//工序移动排序
		remove:function(){
			$('.item-box').sortable({
				placeholder: 'item-placeholder',
				connectWith: '.item-box',
				revert: true
			}).droppable({
				accept: '.item',
				hoverClass: 'item-box-hover',
				drop: function(event, ui){
					setTimeout(function(){
						ui.draggable.removeClass('selected-item');
					}, 500);
				}
			}).disableSelection();
		}
		
}